import os
import sys
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QLineEdit, QFileDialog, QLabel
)
from PyQt5.QtCore import Qt

class FolderChooser(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("选择文件夹示例")
        self.resize(520, 120)

        # 说明文字
        tip = QLabel("点击下方按钮选择一个文件夹：")
        tip.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        # 路径显示框（只读）
        self.path_edit = QLineEdit()
        self.path_edit.setPlaceholderText("未选择")
        self.path_edit.setReadOnly(True)

        # 选择按钮
        self.btn = QPushButton("选择文件夹…")
        self.btn.clicked.connect(self.choose_folder)

        # 布局
        row = QHBoxLayout()
        row.addWidget(self.path_edit)
        row.addWidget(self.btn)

        layout = QVBoxLayout(self)
        layout.addWidget(tip)
        layout.addLayout(row)

    def choose_folder(self):
        # 起始目录设为用户主目录
        start_dir = os.path.expanduser("~")
        # 仅显示文件夹，避免解析符号链接
        options = QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks
        folder = QFileDialog.getExistingDirectory(
            self, "选择文件夹", start_dir, options=options
        )
        if folder:  # 用户点了“确定”
            self.path_edit.setText(folder)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = FolderChooser()
    w.show()
    sys.exit(app.exec_())